package org.example.service.impl;

import org.example.mapper.InventoryMapper;
import org.example.mapper.OrderItemMapper;
import org.example.mapper.OrderMapper;
import org.example.domain.CartItem;
import org.example.domain.FruitInventory;
import org.example.domain.Order;
import org.example.domain.OrderItem;
import org.example.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private InventoryMapper inventoryMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String CART_KEY_PREFIX = "cart:";
    private static final long CART_EXPIRE_DAYS = 7;

    @Override
    public void addToCart(CartItem cartItem) {
        String key = CART_KEY_PREFIX + cartItem.getUserId();
        String hashKey = String.valueOf(cartItem.getId());
        
        // 检查购物车中是否已存在该商品
        CartItem existingItem = (CartItem) redisTemplate.opsForHash().get(key, hashKey);
        
        if (existingItem != null) {
            // 如果已存在，更新数量
            existingItem.setQuantity(existingItem.getQuantity() + cartItem.getQuantity());
            redisTemplate.opsForHash().put(key, hashKey, existingItem);
        } else {
            // 如果不存在，添加新商品
            redisTemplate.opsForHash().put(key, hashKey, cartItem);
        }
        
        // 设置过期时间
        redisTemplate.expire(key, CART_EXPIRE_DAYS, TimeUnit.DAYS);
    }

    @Override
    public void removeFromCart(String userId, Long fruitId) {
        String key = CART_KEY_PREFIX + userId;
        String hashKey = String.valueOf(fruitId);
        redisTemplate.opsForHash().delete(key, hashKey);
    }

    @Override
    public void updateQuantity(String userId, Long fruitId, Integer quantity) {
        String key = CART_KEY_PREFIX + userId;
        String hashKey = String.valueOf(fruitId);
        
        CartItem cartItem = (CartItem) redisTemplate.opsForHash().get(key, hashKey);
        if (cartItem != null) {
            cartItem.setQuantity(quantity);
            redisTemplate.opsForHash().put(key, hashKey, cartItem);
        }
    }

    @Override
    public List<CartItem> getCartItems(String userId) {
        String key = CART_KEY_PREFIX + userId;
        List<Object> values = redisTemplate.opsForHash().values(key);
        List<CartItem> cartItems = new ArrayList<>();
        for (Object value : values) {
            if (value instanceof CartItem) {
                cartItems.add((CartItem) value);
            }
        }
        return cartItems;
    }

    @Override
    public void clearCart(Integer userId) {
        String key = CART_KEY_PREFIX + userId;
        redisTemplate.delete(key);
    }

    @Override
    public boolean checkStock(Long inventoryId, Integer quantity) {
        //查询库存
        FruitInventory fruitInventory = inventoryMapper.selectById(inventoryId);
        BigDecimal stock = fruitInventory.getStock();//当前库存
        BigDecimal need = BigDecimal.valueOf(quantity);
        BigDecimal result = stock.subtract(need);
        if (result.compareTo(BigDecimal.valueOf(0))>0){
            return true;
        }
        return false;
    }

    /***
     * 扣减库存并生成订单
     * @param userId
     * @param items
     */
    @Override
    public void checkout(Integer userId, List<Map<String, Object>> items) {
        // 1. 扣减库存
        for (Map<String, Object> item : items) {
            Long fruitId = Long.valueOf(item.get("id").toString());
            Integer quantity = Integer.valueOf(item.get("quantity").toString());
            
            // 再次检查库存（双重检查）
            if (!checkStock(fruitId, quantity)) {
                throw new RuntimeException("商品库存不足");
            }
            
            // 扣减库存
            FruitInventory inventory = inventoryMapper.selectById(fruitId);
            BigDecimal newStock = inventory.getStock().subtract(BigDecimal.valueOf(quantity));
            inventory.setStock(newStock);
            inventoryMapper.updateById(inventory);
        }
        
        // 2. 生成订单
        Order order = new Order();
        order.setUserId(userId);
        order.setOrderNo(generateOrderNo()); // 生成订单号
        order.setStatus("待支付");
        order.setCreateTime(new Date());
        
        // 计算订单总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        List<OrderItem> orderItems = new ArrayList<>();
        
        for (Map<String, Object> item : items) {
            OrderItem orderItem = new OrderItem();
            orderItem.setFruitId(Long.valueOf(item.get("fruitId").toString()));
            orderItem.setQuantity(Integer.valueOf(item.get("quantity").toString()));
            orderItem.setPrice(new BigDecimal(item.get("price").toString()));
            orderItem.setTotalPrice(orderItem.getPrice().multiply(BigDecimal.valueOf(orderItem.getQuantity())));
            
            totalAmount = totalAmount.add(orderItem.getTotalPrice());
            orderItems.add(orderItem);
        }
        
        order.setTotalAmount(totalAmount);
        
        // 3. 保存订单和订单项
        orderMapper.insert(order);
        
        for (OrderItem orderItem : orderItems) {
            orderItem.setOrderId(order.getId());
            orderItemMapper.insert(orderItem);
        }
        
        // 4. 清空购物车
        clearCart(userId);
    }
    
    /**
     * 生成订单号
     */
    private String generateOrderNo() {
        // 生成规则：时间戳 + 6位随机数
        return System.currentTimeMillis() + String.format("%06d", new Random().nextInt(1000000));
    }

} 